package com.foreknow.filter;

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    private String encoding = "ISO8859-1";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取到配制文件web.xml中filter的局部初始化参数
        encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        //设置服务器端向客户端返回的内容类型
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端请求的字符编码集为utf-8
        req.setCharacterEncoding("utf-8");
        //如果还有其它过滤器，利用filterChain.doFilter(req,resp)方法转交给下一个过滤器，如果没有其它过滤器就要将请求交给对应的Servlet
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
